package com.tang.Date20240613;

import java.util.concurrent.atomic.AtomicInteger;

public class CASExample {
    // 创建一个原子整数变量
    private static AtomicInteger atomicInt = new AtomicInteger(0);

    public static void main(String[] args) {
        // 创建并启动多个线程尝试对atomicInt进行CAS操作
        for (int i = 0; i < 10; i++) {
            new Thread(new CASRunnable()).start();
        }
    }

    static class CASRunnable implements Runnable {
        @Override
        public void run() {
            while (true) {
                // 获取当前值
                int currentValue = atomicInt.get();
                
                // 计算期望的值
                int newValue = currentValue + 1;

                // 使用CAS操作更新值
                boolean success = atomicInt.compareAndSet(currentValue, newValue);

                if (success) {
                    System.out.println(Thread.currentThread().getName() + " updated value to " + newValue);
                    break;
                } else {
                    // 如果CAS操作失败，打印失败信息并重试
                    System.out.println(Thread.currentThread().getName() + " failed to update, retrying...");
                }
            }
        }
    }
}
